package www.dianbaozu.com.ui.manage

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.flatMapConcat
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentChannelEditBinding
import www.dianbaozu.com.extension.requestUniversally
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.KeyHelper.CHANNEL_CREATE_FRAGMENT_UI_KEY
import www.wen.com.common.lib.helper.loading.KeyHelper.GROUP_RESET_SORT_KEY1
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.util.InputFilterUtil


/**
 * @author WEN
 * @Description:频道编辑页面
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class EditChannelFragment : BaseLoadingFragment<FragmentChannelEditBinding>(),
    View.OnClickListener {

    private lateinit var mBundleEntityEditChannelSealed: BundleEntitySealed.BundleEntityEditChannelSealed

    private val mBaseApiViewModel: BaseApiViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = mBaseApiViewModel

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
        requireActivity(),
        tilte = getString(R.string.channel_set),
        isShowRightText = true,
        rightText = getString(R.string.com_save),
        rightTextColor = getColorAgency(R.color.colorFFFFFF),
        action = ::titleAction
    )

    /**
     * 保存频道并更新排序列表的数据
     */
    override fun actionRight() {
        if (dataBinding.etPleaseEnterAGroupName.trimProxy().isBlank()) {
            toast("请输入频道名称")
            return
        }
        mBaseApiViewModel.requestUniversalFlow(
            universalFlow = { appDataManager ->
                appDataManager.patchChannelFlow(
                    channelId = mBundleEntityEditChannelSealed.channelId,
                    RequestBodyParameter(
                        channelDesc = dataBinding.etIntroduction.trimProxy(),
                        channelId = mBundleEntityEditChannelSealed.channelId.toString(),
                        channelName = dataBinding.etPleaseEnterAGroupName.trimProxy(),
                        groupId = mBundleEntityEditChannelSealed.groupId,
                    )
                ).flatMapConcat {
                    appDataManager.serverGroupListFlow(mBundleEntityEditChannelSealed.serverId)
                }
            },
            tipLoading = getString(R.string.be_updating),
            tipSuccess = getString(R.string.update_successfully),
            isShowToastTip = true,
            resultSuccessCall = { groups ->
                val data: MutableList<ServerGroupIncludeEntity> = java.util.ArrayList()
                groups.data.content.forEach {
                    data.add(ServerGroupIncludeEntity(1, it))
                    it.channelVO.forEach { channelVO ->
                        channelVO.groupType = it.groupType
                        data.add(ServerGroupIncludeEntity(2, channelVO = channelVO))
                    }
                }
                //刷新首页-服务分组
                postObject(KeyHelper.REFRESHING_SERVER_LIST_KEY1,Object())
                //刷新频道管理的分组排序
                postObject(KeyHelper.GROUP_RESET_SORT_KEY, ServerGroupListEntity(data))
                //刷新首页-服务器,防止返回的时候仍然看到已删除的频道
                postObject(KeyHelper.REFRESHING_SERVER_LIST_KEY6, mBundleEntityEditChannelSealed.serverId)
            }
        )
    }

    override fun getLayoutId(): Int = R.layout.fragment_channel_edit

    override fun lazyInitView() {
        mBundleEntityEditChannelSealed = requireArguments().getParcelable(BUNDLE_DATA)!!
        dataBinding.run {
            etPleaseEnterAGroupName.filters = InputFilterUtil().excludedExpression().excludedN().maxLength(16).build()
            etIntroduction.filters = InputFilterUtil().excludedExpression().excludedN().maxLength(20).build()
            etPleaseEnterAGroupName.setText(mBundleEntityEditChannelSealed.channelName)
            etIntroduction.setText(mBundleEntityEditChannelSealed.channelDesc)
            tvGroupName.text = mBundleEntityEditChannelSealed.groupName
        }
        observeListen()
    }

    /**
     * 更新分组名称
     */
    private fun observeListen() {
        observeObject(CHANNEL_CREATE_FRAGMENT_UI_KEY, this, GroupingEntity::class.java) {
            dataBinding.tvGroupName.text = groupName
            mBundleEntityEditChannelSealed.groupId = groupId
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tvGroupName -> selectGroup()
            R.id.tvDeleteChannel -> deleteChannel()
        }
    }

    /**
     * 删除分组
     */
    private fun deleteChannel() {
        CreateXPopupHelper.createShowStandardAlertPopupView(PopupViewEntity().apply {
            context = requireActivity()
            standardAlertPopupViewTitle = getString(R.string.com_delete_channel)
            isShow = true
            standardAlertPopupViewCancelContent = "取消"
            standardAlertPopupViewConfirmContent = "确认"
            standardAlertPopupViewContent = "你确定删除该频道吗？\n\n该操作无法撤销"
            confirmFunction = { basePopupView ->
                mBaseApiViewModel.requestUniversally(
                    viewModelScope = lifecycleScope,
                    isShowToastTip = false,
                    request = { appDataManage ->
                        appDataManage.deleteChannel(channelId = mBundleEntityEditChannelSealed.channelId)
                    }
                ) { channelInfo ->
                    basePopupView.dismiss()
                    //移除列表的频道并返回上一页
                    postObject(GROUP_RESET_SORT_KEY1, mBundleEntityEditChannelSealed.position)
                    //刷新首页-服务器,防止返回的时候仍然看到已删除的频道
                    postObject(KeyHelper.REFRESHING_SERVER_LIST_KEY6, mBundleEntityEditChannelSealed.serverId)
                    actionLeft()
                }
            }
        })
    }

    /**
     * 选择分组
     */
    private fun selectGroup() {
        mBaseApiViewModel.requestUniversally(
            viewModelScope = lifecycleScope,
            isShowToastTip = false,
            request = { appDataManage ->
                appDataManage.requestServerGroup(mBundleEntityEditChannelSealed.serverId)
            }
        ) { groups ->
            nav(R.id.action_editChannelFragment_to_groupingSortingFragment, Bundle().apply {
                groups.first { group ->
                    mBundleEntityEditChannelSealed.groupId == group.groupId
                }.also {
                    it.isSelected = true
                    putParcelableArrayList(BUNDLE_DATA, groups as ArrayList<GroupingEntity>)
                }
            })
        }
    }

}



